package com.code.aspectj.aspectj;

import android.os.Looper;

import com.code.aspectj.annotation.ThreadIO;
import com.code.aspectj.util.Executors;
import com.code.aspectj.util.ReflectUtils;
import com.code.aspectj.util.P;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import static com.code.aspectj.AppInterceptor.TAG;


/**
 * Created by RLZ
 * on 2021/12/8
 * 子线程执行
 */

@Aspect
public class ThreadAspect {


    @Pointcut("within(@com.code.aspectj.annotation.ThreadIO *)")
    public void withinAnnotatedClass() {
    }

    @Pointcut("execution(!synthetic * *(..)) && withinAnnotatedClass()")
    public void methodInsideAnnotatedType() {
    }

    @Pointcut("execution(@com.code.aspectj.annotation.ThreadIO * *(..)) || methodInsideAnnotatedType()")
    public void method() {
    }  //方法切入点

    @Around("method() && @annotation(ioThread)")//在连接点进行方法替换
    public Object aroundJoinPoint(final ProceedingJoinPoint joinPoint, ThreadIO ioThread) throws Throwable {
        if (Looper.getMainLooper() != Looper.myLooper()) {
            return joinPoint.proceed();
        } else {
            P.d(TAG, ReflectUtils.getMethodDescribeInfo(joinPoint) + " \u21E2 [当前线程]:"
                    + Thread.currentThread().getName() + "，正在切换到子线程！");
            Object result = null;
            switch (ioThread.value()) {
                case SINGLE:
                    result = Executors.get().singleIO().submit(() -> getProceedResult(joinPoint)).get();
                    break;
                case FIXED:
                    result = Executors.get().poolIO().submit(() -> getProceedResult(joinPoint)).get();
                    break;
                default:
                    break;
            }
            P.d(TAG, ReflectUtils.getMethodDescribeInfo(joinPoint));
            return result;
        }
    }

    /**
     * 获取执行结果
     */
    private Object getProceedResult(ProceedingJoinPoint joinPoint) {
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            P.e(TAG, e);
        }
        return null;
    }

}
